/*
 * @Description: Description
 * @Autor: Chen
 * @Date: 2020-08-07 09:04:17
 * @LastEditors: snzo.chen
 * @LastEditTime: 2021-09-24 16:29:35
 */
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { AnyJson } from './data-types/common.type';

@Injectable({
  providedIn: 'root',
})
export class StorageService {
  private isBrowser: boolean;
  constructor(@Inject(PLATFORM_ID) private plateformId: object) {
    this.isBrowser = isPlatformBrowser(this.plateformId);
  }
  getStorage(key: string): string | null {
    if (this.isBrowser) {
      return window.localStorage.getItem(key);
    } else {
      return '';
    }
  }
  setStorage(params: AnyJson | AnyJson[]) {
    if (this.isBrowser) {
      const kv = Array.isArray(params) ? params : [params];
      for (const { key, value } of kv) {
        window.localStorage.setItem(key, value.toString());
      }
    }
  }
  removeStorage(params: string | string[]) {
    if (this.isBrowser) {
      const kv = Array.isArray(params) ? params : [params];
      for (const key of kv) {
        window.localStorage.removeItem(key);
      }
    }
  }

  getSessionStorage(key: string): string | null {
    if (this.isBrowser) {
      return window.sessionStorage.getItem(key);
    } else {
      return '';
    }
  }

  setSessionStorage(params: AnyJson | AnyJson[]) {
    if (this.isBrowser) {
      const kv = Array.isArray(params) ? params : [params];
      for (const { key, value } of kv) {
        window.sessionStorage.setItem(key, value.toString());
      }
    }
  }
}
